package thread;

/**
 * @description: 线程通信问题，两线程交替打印1-100
 * @author: apple
 * @date:  2021/11/28 9:01 下午
 * @version 1.0
 **/
public class CommunicationTest {
    public static void main(String[] args) {
        N n = new N();
        Thread t1 = new Thread(n , "第1个线程");
        Thread t2 = new Thread(n , "第2个线程");
        t1.start();
        t2.start();
    }
}

class N implements Runnable {

    private int start = 1;

    @Override
    public void run() {

        while (true) {
            // 这里的this代表N的对象
            synchronized(this) {
                this.notify(); //唤醒wait优先级高的1个线程
                if (start <= 100) {
                    System.out.println(Thread.currentThread().getName() + ":" + start);
                    start++;
                    try {
                        // 当前执行的线程进入阻塞状态，并释放锁
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    break;
                }
            }
        }
    }
}
